package com.buddy.learn.spring.framework.aop;

import com.buddy.learn.spring.framework.aop.intercept.BMethodInvocation;
import com.buddy.learn.spring.framework.aop.support.BAdvisedSupport;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * 生成代理对象
 */
public class BJdkDynamicAopProxy implements BAopProxy, InvocationHandler {


    private BAdvisedSupport advised;

    public BJdkDynamicAopProxy(BAdvisedSupport config) {
        this.advised = config;
    }


    @Override
    public Object getProxy() {
        return getProxy(this.advised.getTargetClass().getClassLoader());
    }

    @Override
    public Object getProxy(ClassLoader classLoader) {

        //获取代理对象，JDK动态代理，代理模式通过classLoader生成字节码重新生成一个类，invoke方法
        return Proxy.newProxyInstance(classLoader, this.advised.getTargetClass().getInterfaces(), this);
    }

    //前后增强，责任链模式
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        List<Object>  interceptorsAndDynamicMethodMatcher = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method,this.advised.getTargetClass());

        BMethodInvocation invocation = new BMethodInvocation(proxy,this.advised.getTargetClass(), method,
                args, this.advised.getTargetClass(), interceptorsAndDynamicMethodMatcher);
        return invocation.proceed();
    }
}
